<template>
  <div>
    <el-dialog :title="userSelectDialog.title" v-model="userSelectDialog.visible" width="60%" append-to-body>
      <el-row type="flex" :gutter="20">
        <!--部门数据-->
        <el-col :span="5">
          <el-card shadow="never" style="height: 100%">
            <template #header>
              <span>部门列表</span>
            </template>
            <div>
              <el-input v-model="deptName" placeholder="请输入部门名称" prefix-icon="Search" clearable />
              <el-tree
                :data="deptOptions"
                :props="{label: 'label', children: 'children'}"
                :expand-on-click-node="false"
                :filter-node-method="filterNode"
                ref="deptTreeRef"
                default-expand-all
                @node-click="handleNodeClick"
              />
            </div>
          </el-card>
        </el-col>
        <el-col :span="18">
          <el-table
            ref="userTableRef"
            :key="userSelectType"
            height="400"
            v-loading="userLoading"
            :data="userList"
            highlight-current-row
            :row-key="getRowKeys"

            @selection-change="handleSelectionChange"
          >
            <el-table-column v-if="userSelectType === 'copy' || userSelectType === 'next' || userSelectType === 'addSign'"
              :reserve-selection="true" width="55" type="selection" />
            <!--<el-table-column v-else width="30">
              <template #default="scope">
                <el-radio :label="scope.row.userId" v-model="currentUserId">{{''}}</el-radio>
              </template>
            </el-table-column>-->
            <el-table-column label="用户名称" align="center" prop="userName" />
            <el-table-column label="用户昵称" align="center" prop="nickName" />
            <el-table-column label="手机" align="center" prop="phonenumber" />
          </el-table>
          <pagination :total="userTotal" v-model:page="queryUserParams.pageNum" v-model:limit="queryUserParams.pageSize" @pagination="getList" />
        </el-col>
      </el-row>
      <template #footer>
        <el-button @click="userSelectDialog.visible = false">取 消</el-button>
        <el-button type="primary" @click="submitUserData">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="UserSelect" lang="ts">

  import { ComponentInternalInstance } from "vue";
  import { UserVO, DeptVO } from "@/api/workflow/identity/types";
  import { deptTreeSelect } from "@/api/workflow/identity";
  import { selectUser } from "@/api/system/user";

  const { proxy } = getCurrentInstance() as ComponentInternalInstance;

  const userList = ref<UserVO[]>([]);
  const userLoading = ref(false);
  const userTotal = ref(0);
  const userSelectType = ref();
  const deptName = ref('');
  const deptOptions = ref<DeptVO[]>([]);
  const dateRange = ref<[DateModelType, DateModelType]>(['', '']);
  // 查询参数
  const queryUserParams = ref({
    pageNum: 1,
    pageSize: 10,
    deptId: ''
  })
  const userSelectDialog = reactive<DialogOption>({
    visible: false,
    title: ''
  });
  const deptTreeRef = ref(null);
  const userTableRef = ref<ElTableInstance>();

  const props = defineProps({
    multiple: {
      type: Boolean,
      default: () => {
        return true
      }
    },
    modelValue: {
      type: UserVO | undefined,
      default: () => {
        return undefined
      }
    },
    data: {
      type: string | number,
      default: () => {
        return undefined
      }
    }
  })

  const emit = defineEmits(['update:modelValue', 'submitUserDataCallBack']);

  /** 通过条件过滤节点  */
  const filterNode = (value: string, data: any) => {
    if (!value) return true
    return data.label.indexOf(value) !== -1
  }

  // 节点单击事件
  const handleNodeClick = (data: any) => {
    queryUserParams.value.deptId = data.id;
    getList();
  }
  /** 查询部门下拉树结构 */
  const getTreeSelect = async () => {
    const res = await deptTreeSelect();
    deptOptions.value = res.data;
  };
  /** 查询用户列表 */
  const getList = async () => {
    userLoading.value = true;
    const res = await selectUser(proxy?.addDateRange(queryUserParams.value, dateRange.value));
    userList.value = res.rows;
    userTotal.value = res.total;
    //toggleSelection(userMultipleSelection.value);
    userLoading.value = false;
  }

  function getRowKeys(row) {
    return row.userId  // 指定table id
  }

  const changeCurrentUser = (val: any) => {
    currentUserId.value = val?.userId
  }
  const handleSelectionChange = (selection) => {
    userMultipleSelection.value = selection
  }
  const toggleSelection = (selection) => {
    console.log("toggleSelection selection",selection)
    if (selection && selection.length > 0) {
      nextTick(()=> {
        selection.forEach(item => {
          console.log("toggleSelection item",item)
          let row = userList.value.find(k => k.userId === item.userId);
          console.log("toggleSelection row",row)
          if(row === undefined) return;
          userTableRef.value.toggleRowSelection(row);
        })
      })
    } else {
      nextTick(() => {
        userTableRef.value?.clearSelection();
      });
    }
  }

  const submitUserData = () => {
    emit('update:modelValue', selectUserList.value);
    emit('submitUserDataCallBack', selectUserList.value);
    userSelectDialog.visible = false;
  };

</script>

<style>
</style>
